import logging
import pickle
import re
import json

logger = logging.getLogger(__name__)

from PySide6.QtCore import QThread, Signal

class ColumnNameMatcher(QThread):

    result = Signal(bytes)
    target_columns = [
        "最小电压",
        "最小电压节数",
        "最大电压",
        "最大电压节数",
        "最小温度",
        "最小温度节数",
        "最大温度",
        "最大温度节数",
        "SOC"
    ]

    from_columns = []

    def set_from_columns(self, from_columns):
        self.from_columns = from_columns

    def load_keyword_map(self):
        """从JSON文件加载关键词映射"""
        try:
            with open('static/key_map.json', 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            logger.warning("未找到static/key_map.json文件，使用默认关键词映射")
            # 返回默认的关键词映射
            return {
                "最小电压": ["min", "volt", "voltage", "v", "batt", "cell"],
                "最小电压节数": ["min", "num", "index", "volt", "voltage", "batt", "cell", "location", "index"],
                "最大电压": ["max", "volt", "voltage", "v", "batt", "cell"],
                "最大电压节数": ["max", "num", "index", "volt", "voltage", "batt", "cell", "location", "index"],
                "最小温度": ["min", "temp", "temperature", "t"],
                "最小温度节数": ["min", "num", "index", "temp", "temperature", "location", "index"],
                "最大温度": ["max", "temp", "temperature", "t"],
                "最大温度节数": ["max", "num", "index", "temp", "temperature", "location", "index"],
                "SOC": ["soc"]
            }
        except json.JSONDecodeError:
            logger.error("static/key_map.json文件格式错误，使用默认关键词映射")
            # 返回默认的关键词映射
            return {
                "最小电压": ["min", "volt", "voltage", "v", "batt", "cell"],
                "最小电压节数": ["min", "num", "index", "volt", "voltage", "batt", "cell", "location", "index"],
                "最大电压": ["max", "volt", "voltage", "v", "batt", "cell"],
                "最大电压节数": ["max", "num", "index", "volt", "voltage", "batt", "cell", "location", "index"],
                "最小温度": ["min", "temp", "temperature", "t"],
                "最小温度节数": ["min", "num", "index", "temp", "temperature", "location", "index"],
                "最大温度": ["max", "temp", "temperature", "t"],
                "最大温度节数": ["max", "num", "index", "temp", "temperature", "location", "index"],
                "SOC": ["soc"]
            }

    def run(self):
        signals = []
        # 从JSON文件加载关键词映射
        keyword_map = self.load_keyword_map()

        # 遍历每个目标列，寻找匹配的列名
        for target in self.target_columns:
            keywords = keyword_map.get(target, [])
            best_match = None
            best_score = 0
            best_length = float('inf')  # 初始化最佳长度为无穷大

            for column in self.from_columns:
                # 跳过中文字符超过两个的列名
                if len(re.findall(r'[\u4e00-\u9fff]', column)) > 2:
                    continue

                lower_column = column.lower()
                score = 0
                # 计算匹配得分：每个匹配的关键词加1分
                for keyword in keywords:
                    if keyword in lower_column:
                        score += 1

                # 如果当前列名得分更高，或者得分相同但长度更短，则更新最佳匹配
                if score > best_score or (score == best_score and len(column) < best_length):
                    best_score = score
                    best_match = column
                    best_length = len(column)  # 更新最佳长度

            # 如果找到匹配，则使用该列名；否则设为None
            if best_score > 0:
                signals.append(best_match)
            else:
                signals.append("")
        self.result.emit(pickle.dumps(signals))